package com.manage.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manage.dto.RoleDTO;
import com.manage.dto.add.RoleAddDTO;
import com.manage.dto.update.RoleUpdateDTO;
import com.manage.entity.Role;
import com.manage.result.PageResult;
import com.manage.server.mapper.RoleMapper;
import com.manage.server.service.RoleService;
import com.manage.vo.RoleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @description 针对表【role(身份表)】的数据库操作Service实现
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public boolean save(RoleAddDTO roleAddDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleAddDTO, role);
        return this.save(role);
    }

    @Override
    public boolean updateById(RoleUpdateDTO roleUpdateDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateDTO, role);
        return super.updateById(role);
    }

    @Override
    public PageResult<RoleVO> findRoleByPage(RoleDTO dto) {
        // 1. 处理分页参数（默认第1页，每页10条）
        int pageNum = dto.getPageNum() != null && dto.getPageNum() > 0 ? dto.getPageNum() : 1;
        int pageSize = dto.getPageSize() != null && dto.getPageSize() > 0 ? dto.getPageSize() : 10;

        // 2. 创建分页对象
        Page<Role> page = new Page<>(pageNum, pageSize);

        // 3. 构建动态查询条件
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();

        // 精确匹配条件
        if (dto.getId() != null) {
            queryWrapper.eq("id", dto.getId());
        }
        if (dto.getDepartmentId() != null) {
            queryWrapper.eq("department_id", dto.getDepartmentId());
        }
        if (dto.getPositionId() != null) {
            queryWrapper.eq("position_id", dto.getPositionId());
        }

        // 4. 执行分页查询
        Page<Role> resultPage = this.page(page, queryWrapper);

        // 5. 转换Entity到VO
        Page<RoleVO> voPage = (Page<RoleVO>) resultPage.convert(entity -> {
            RoleVO vo = new RoleVO();
            BeanUtils.copyProperties(entity, vo);
            // 可在此处理字段不一致的情况
            return vo;
        });

        // 6. 返回分页结果
        return PageResult.success(voPage);
    }
}